package com.flypigs.lock;

import lombok.extern.slf4j.Slf4j;
import org.ehcache.expiry.ExpiryPolicy;

import java.time.Duration;
import java.util.function.Supplier;

/**
 * @author Andy.yang
 * @version v1
 * @summary
 * @Copyright (c) 2019, YueYang Group All Rights Reserved.
 * @since 2020/5/12
 */
@Slf4j
public class EhcacheValueExpiryPolicy implements ExpiryPolicy<Object,EhcacheValue> {
    //存活时间：从创建时算起
    private final Duration create;
    //存活时间：从最后一次查询算起
    private final Duration access;
    //存活时间：从最后更新算起
    private final Duration update;

    public EhcacheValueExpiryPolicy(Duration create, Duration access, Duration update) {
        this.create = create;
        this.access = access;
        this.update = update;
    }

    @Override
    public Duration getExpiryForCreation(Object key, EhcacheValue ehcacheValue) {
        if(ehcacheValue.getTimeToLive() < 0){
            return create;
        }
        return Duration.ofSeconds(ehcacheValue.getTimeToLive());
    }

    @Override
    public Duration getExpiryForAccess(Object key, Supplier<? extends EhcacheValue> ehcacheValue) {
        return null;
    }

    @Override
    public Duration getExpiryForUpdate(Object key, Supplier<? extends EhcacheValue> oldValue, EhcacheValue newValue) {
        if(newValue.getTimeToLive() < 0){
            return update;
        }
        return Duration.ofSeconds(newValue.getTimeToLive());
    }
}
